/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/* 
 * gximclient.c
 * Copyright (C) 2008 Akira TAGOH
 * 
 * Authors:
 *   Akira TAGOH  <akira@tagoh.org>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif /* HAVE_STRING_H */
#include "gximclconn.h"
#include "gximerror.h"
#include "gximmessage.h"
#include "gximmisc.h"
#include "gximclient.h"


#define G_XIM_CLIENT_GET_PRIVATE(_o_)		(G_TYPE_INSTANCE_GET_PRIVATE ((_o_), G_TYPE_XIM_CLIENT, GXimClientPrivate))

enum {
	PROP_0,
	LAST_PROP
};
enum {
	SIGNAL_0,
	LAST_SIGNAL
};

struct _GXimClientPrivate {
	GdkWindow  *server_window;
	GdkAtom     atom_server;
	guint       is_locale_initialized;
	guint       is_transport_initialized;
	guint       is_connection_initialized;
	gchar     **locales;
	gchar     **transport;
};

//static guint signals[LAST_SIGNAL] = { 0 };

G_DEFINE_TYPE (GXimClient, g_xim_client, G_TYPE_XIM_CL_TMPL);

/*
 * Private functions
 */
static void
g_xim_client_real_set_property(GObject      *object,
			       guint         prop_id,
			       const GValue *value,
			       GParamSpec   *pspec)
{
	switch (prop_id) {
	    default:
		    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		    break;
	}
}

static void
g_xim_client_real_get_property(GObject    *object,
			       guint       prop_id,
			       GValue     *value,
			       GParamSpec *pspec)
{
	switch (prop_id) {
	    default:
		    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		    break;
	}
}

static void
g_xim_client_real_finalize(GObject *object)
{
	if (G_OBJECT_CLASS (g_xim_client_parent_class)->finalize)
		(* G_OBJECT_CLASS (g_xim_client_parent_class)->finalize) (object);
}

static void
g_xim_client_real_setup_connection(GXimCore       *core,
				   GXimConnection *conn)
{
}

static void
g_xim_client_real_notify_locales(GXimClientTemplate  *client,
				 gchar              **locales)
{
	GXimClientPrivate *priv = G_XIM_CLIENT_GET_PRIVATE (client);
	GXimCore *core = G_XIM_CORE (client);

	priv->locales = g_strdupv(locales);
	g_xim_cl_tmpl_send_selection_request(client,
					     core->atom_transport,
					     NULL);
}

static void
g_xim_client_real_notify_transport(GXimClientTemplate  *client,
				   gchar              **transport)
{
	GXimClientPrivate *priv = G_XIM_CLIENT_GET_PRIVATE (client);

	priv->transport = g_strdupv(transport);
	g_xim_cl_tmpl_connect_to_server(client, NULL);
}

static void
g_xim_client_class_init(GXimClientClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	GXimCoreClass *core_class = G_XIM_CORE_CLASS (klass);
	GXimClientTemplateClass *cltmpl_class = G_XIM_CL_TMPL_CLASS (klass);

	g_type_class_add_private(klass, sizeof (GXimClientPrivate));

	object_class->set_property = g_xim_client_real_set_property;
	object_class->get_property = g_xim_client_real_get_property;
	object_class->finalize     = g_xim_client_real_finalize;

	core_class->setup_connection = g_xim_client_real_setup_connection;

	cltmpl_class->notify_locales   = g_xim_client_real_notify_locales;
	cltmpl_class->notify_transport = g_xim_client_real_notify_transport;

	/* properties */

	/* signals */
}

static void
g_xim_client_init(GXimClient *client)
{
	GXimClientPrivate *priv = G_XIM_CLIENT_GET_PRIVATE (client);
	GXimLazySignalConnector sigs[] = {
		{NULL, NULL, NULL}
	};
	const gchar *xmodifiers;
	gsize len;

	g_object_set(client, "proto_signals", sigs, NULL);
	xmodifiers = g_getenv("XMODIFIERS");
	len = (xmodifiers ? strlen(xmodifiers) : 0);
	if (len > 4 && strncmp(xmodifiers, "@im=", 4) == 0) {
		gchar *s, *im_name = g_strdup(&xmodifiers[4]);

		s = g_strdup_printf("@server=%s", im_name);
		priv->atom_server = gdk_atom_intern(s, FALSE);
		g_free(s);
		g_free(im_name);
	}
}

/*
 * Public functions
 */
GQuark
g_xim_client_get_error_quark(void)
{
	static GQuark quark = 0;

	if (!quark)
		quark = g_quark_from_static_string("g-xim-client-error");

	return quark;
}

GXimClient *
g_xim_client_new(GdkDisplay  *dpy,
		 const gchar *server_name)
{
	GXimClient *retval;
	GdkAtom atom_server;
	GError *error = NULL;

	g_return_val_if_fail (GDK_IS_DISPLAY (dpy), NULL);
	g_return_val_if_fail (server_name != NULL, NULL);

	atom_server = g_xim_get_server_atom(server_name);
	retval = G_XIM_CLIENT (g_object_new(G_TYPE_XIM_CLIENT,
					    "display", dpy,
					    "connection_gtype", G_TYPE_XIM_CLIENT_CONNECTION,
					    "atom_server", atom_server,
					    NULL));
	if (retval == NULL)
		return NULL;
	if (!g_xim_cl_tmpl_start_negotiation(G_XIM_CL_TMPL (retval), &error)) {
		g_xim_message_critical(G_XIM_CORE (retval)->message,
				       "Unable to negotiate to the XIM server: %s",
				       error->message);
		g_error_free(error);
		g_object_unref(retval);

		return NULL;
	}

	return retval;
}

gboolean
g_xim_client_is_initialized(GXimClient *client)
{
	return g_xim_cl_tmpl_is_initialized(G_XIM_CL_TMPL (client));
}

gboolean
g_xim_client_open_im(GXimClient *client)
{
	GXimClientPrivate *priv;
	GXimClientConnection *conn;
	const gchar *locale = setlocale(LC_CTYPE, NULL);
	gchar *tmp_locale, *tmp;
	gint i;

	g_return_val_if_fail (G_IS_XIM_CLIENT (client), FALSE);
	g_return_val_if_fail (locale != NULL, FALSE);
	g_return_val_if_fail (!g_xim_client_is_initialized(client), FALSE);

	priv = G_XIM_CLIENT_GET_PRIVATE (client);
	while (g_xim_cl_tmpl_is_pending_negotiation(G_XIM_CL_TMPL (client))) {
		g_main_context_iteration(NULL, TRUE);
	}
	g_return_val_if_fail (g_xim_client_is_initialized(client), FALSE);

	conn = G_XIM_CLIENT_CONNECTION (G_XIM_CL_TMPL (client)->connection);
	if (!g_xim_client_connection_connect(conn, 1, 0, /* FIXME */NULL, FALSE))
		return FALSE;

	for (i = 0; priv->locales[i]; i++) {
		if (g_ascii_strcasecmp(locale, priv->locales[i]) == 0) {
			gboolean retval;
			GXimStr *str;

			str = g_xim_str_new();
			G_XIM_CHECK_ALLOC (str, FALSE);

			g_xim_str_append(str, locale);

			retval = g_xim_client_connection_open_im(conn, str, FALSE);
			g_xim_str_free(str);

			return retval;
		}
	}

	/* Strip the locale code down to the essentials */
	tmp_locale = g_strdup(locale);
	tmp = strchr(tmp_locale, '.');
	if (tmp)
		*tmp = 0;
	tmp = strchr(tmp_locale, '@');
	if (tmp)
		*tmp = 0;

	for (i = 0; priv->locales[i]; i++) {
		if (g_ascii_strcasecmp(tmp_locale, priv->locales[i]) == 0) {
			gboolean retval;
			GXimStr *str;

			str = g_xim_str_new();
			G_XIM_CHECK_ALLOC (str, FALSE);

			g_xim_str_append(str, tmp_locale);

			retval = g_xim_client_connection_open_im(conn, str, FALSE);
			g_xim_str_free(str);
			g_free(tmp_locale);

			return retval;
		}
	}
	g_free(tmp_locale);

	g_xim_message_warning(G_XIM_CORE (client)->message,
			      "XIM server doesn't support current locale: %s",
			      locale);

	return FALSE;
}
